package edu.task.snake.controller;

import edu.task.snake.model.Arena;
import edu.task.snake.model.Cell;
import edu.task.snake.model.Frog;
import edu.task.snake.model.Snake;
import edu.task.snake.view.FrogRender;
import edu.task.snake.view.SnakeRender;
import edu.task.snake.view.ViewArena;

import java.util.ArrayList;
import java.util.List;


public class GameEngine {

    public static final int DOT_SIZE = 15;// todo cell size

    private List<Frog> frogList = new ArrayList<Frog>();
    Snake snake = new Snake();
    SnakeController snakeController;

    int xArea = 30;
    int yArea = 30;
    Arena arena = new Arena(xArea, yArea);
    //ForGameEngine
    FrogRender frogRenderer;
    SnakeRender snakeRender;

    ViewArena viewArena;

    public ViewArena getViewArena() {
        return viewArena;
    }

    private boolean inGame = true;

    public GameEngine() {

        initGame();

        frogRenderer = new FrogRender(viewArena);
        snakeRender = new SnakeRender(viewArena, snake);
        viewArena = new ViewArena(xArea * DOT_SIZE, yArea * DOT_SIZE, snakeRender, frogRenderer, frogList, arena);
        viewArena.addKeyListener(new KAdapter(snakeController));
        viewArena.addMouseListener(new MAdapter(snakeController));

        snakeController.start();
    }

    private void initGame() {
        initSnake();

        for (int i = 0; i < 14; i++) {
            frogList.add(initFrog());
        }
    }

    private void initSnake() {
        ArrayList<Cell> cells = new ArrayList<Cell>();
        cells.add(new Cell(1, 0)); //initialise with params
        cells.add(new Cell(2, 0));
        cells.add(new Cell(3, 0));
        snake.setArrayList(cells);
        snakeController = new SnakeController(snake, this);
    }

    public Frog initFrog() {

        Frog frog = new Frog();
        int r = (int) (Math.random() * xArea);
        frog.setX(r);
        r = (int) (Math.random() * yArea);
        frog.setY(r);
        return frog;
    }

    public void doDrawing() {// todo draw
        if (inGame) {
            viewArena.render();
        } else {
            viewArena.gameOver();
        }
    }

    public void checkFreeSpace() {
        // ToDo можно ли расположить еще лягушку или игра закончилась Hero Win!
    }

    public List<Frog> getFrogList() {
        return frogList;
    }

    public boolean isInGame() {
        return inGame;
    }

    public void setInGame(boolean inGame) {
        this.inGame = inGame;
    }

    public int getXArea() {
        return xArea;
    }

    public int getYArea() {
        return yArea;
    }

    public void stopGame() {

    }
}
